<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/8 0008
 * Time: 下午 1:49
 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Validator;
use Session;
use Illuminate\Support\Facades\Storage;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Models\AppointmentModel;
use App\Http\Models\UserModel;
use PHPExcel;

class AppointmentController extends Controller
{
    public function index(Request $request)
    {

        if ($request->isMethod('get')) {
            $data['data'] = AppointmentModel::select('appointment.*', 'user.role', 'user.name', 'user.school', 'user.college', 'user.student_num', 'user.dormitory')
                ->join('user', 'appointment.openid', '=', 'user.openid')
                ->paginate(10);
            $data['type'] = 3;
            return view('order.appointment', compact('data'));
        } else {
            $where = $request->only('role', 'datemax', 'datemin');
            $where = $this->where_data($where);
            if (!empty($where)) {
                if (isset($where['datemax'])) {
                    $datemax = $where['datemax'];
                }
                if (isset($where['datemin'])) {
                    $datemin = $where['datemin'];
                }
                unset($where['datemax']);
                unset($where['datemin']);
                if (!empty($datemax) && !empty($datemin)) {
                    $data['data'] = AppointmentModel::whereBetween('create_time', array($datemin, $datemax))
                        ->paginate(10);
                } elseif (!empty($datemin)) {

                    $data['data'] = AppointmentModel::where('create_time', '>', $datemin)
                        ->paginate(10);
                } elseif (!empty($datemax)) {
                    $data['data'] = AppointmentModel::where('create_time', '<', $datemax)
                        ->paginate(10);
                }
                if (!empty($data['data']) && empty($where['role'])) {
                    foreach ($data['data'] as $key => $value) {
                        $user_info = UserModel::where('openid', $value['openid'])->first();
                        $data['data'][$key]['name'] = $user_info->name;
                        $data['data'][$key]['nikename'] = $user_info->nikename;
                        $data['data'][$key]['mobile'] = $user_info->mobile;
                        $data['data'][$key]['school'] = $user_info->school;
                        $data['data'][$key]['dormitory'] = $user_info->dormitory;
                        $data['data'][$key]['college'] = $user_info->college;
                        $data['data'][$key]['student_num'] = $user_info->student_num;
                    }
                } elseif (!empty($data['data']) && !empty($where['role'])) {
                    foreach ($data['data'] as $key => $value) {
                        $user_info = UserModel::where(['openid'=> $value['openid'],'role'=>$where['role']])->first();
                        $data['data'][$key]['name'] = $user_info->name;
                        $data['data'][$key]['nikename'] = $user_info->nikename;
                        $data['data'][$key]['mobile'] = $user_info->mobile;
                        $data['data'][$key]['school'] = $user_info->school;
                        $data['data'][$key]['dormitory'] = $user_info->dormitory;
                        $data['data'][$key]['college'] = $user_info->college;
                        $data['data'][$key]['student_num'] = $user_info->student_num;
                    }
                }

            } else {
                $data['data'] = AppointmentModel::select('appointment.*', 'user.role', 'user.name', 'user.school', 'user.college', 'user.student_num', 'user.dormitory')
                    ->join('user', 'appointment.openid', '=', 'user.openid')
                    ->paginate(10);
            }
            if ($request->input('status') == 1) {
                if (!empty($data['data'])) {
                    $data = $data['data']->toArray();
                   // dd($data);
                    $this->save_excel($data['data']);
                }
            }
            $data['type'] = 3;

            return view('order.appointment', compact('data'));
        }
    }

    public function get_order_index(Request $request)
    {
        $where = $request->only('role', 'express_id', 'datemax', 'datemin');
        $where = $this->where_data($where);
        if (!empty($where)) {
            if (isset($where['datemax'])) {
                $datemax = $where['datemax'];

            } else {

            }
            if (isset($where['datemin'])) {
                $datemin = $where['datemin'];

            }
            unset($where['datemax']);
            unset($where['datemin']);
            if (!empty($datemax) && !empty($datemin)) {
                $data['data'] = OrderModel::whereBetween('create_time', array($datemin, $datemax))
                    ->where($where)
                    ->paginate(10);
                //dd( $data['data']);
            } elseif (!empty($datemin)) {

                $data['data'] = OrderModel::where('create_time', '>', $datemin)
                    ->where($where)
                    ->paginate(10);
            } elseif (!empty($datemax)) {
                $data['data'] = OrderModel::where('create_time', '<', $datemax)
                    ->where($where)
                    ->paginate(10);
            } else {
                $data['data'] = OrderModel::where($where)
                    ->paginate(10);
            }

            if (!empty($data['data']))
                foreach ($data['data'] as $key => $value) {
                    $user_info = UserModel::where('openid', $value['openid'])->first();
                    $data['data'][$key]['name'] = $user_info->name;
                    $data['data'][$key]['nikename'] = $user_info->nikename;
                    $data['data'][$key]['mobile'] = $user_info->mobile;
                }

        } else {
            $data['data'] = OrderModel::select('order.*', 'user.name', 'user.nikename', 'user.mobile')
                ->join('user', 'order.openid', '=', 'user.openid')
                ->paginate(10);
        }
        if ($request->input('status') == 1) {

            if (!empty($data['data'])) {
                $data = $data['data']->toArray();
                $this->save_excel($data['data']);
            }
        }
        $data['type'] = 3;


    }


    public function where_data($data)
    {
        foreach ($data as $k => $v) {
            if (empty($v)) {
                unset($data[$k]);
            }
        }
        if (isset($data['datemax']))
            $data['datemax'] = strtotime($data['datemax']) + 3600 * 24;
        if (isset($data['datemin']))
            $data['datemin'] = strtotime($data['datemin']);
        return $data;
    }


    public function edit(Request $request, $id)
    {

    }

    public function del(Request $request)
    {
        $id = $request->input('id');
        $res = AppointmentModel::where(['id' => $id])->first();

        if (!empty($res)) {
            AppointmentModel::where(['id' => $id])->delete();
            return response()->json(['status' => 200, 'msg' => '删除成功']);
        }
        return response()->json(['status' => 500, 'msg' => '删除失败']);

    }

    //输出数据保存excel
    public  function  save_excel($data){

        foreach ($data as $k =>$v){
            if($v['role']==1){
                $data[$k]['role'] ='教师';
            }else{
                $data[$k]['role'] ='学生';
            }
            if($v['status']!=0){
                $data[$k]['status'] ='快递员已查看';
            }else{
                $data[$k]['status'] ='快递员待查看';
            }
            $data[$k]['create_time'] =date('Y-m-d H:i:s',$v['create_time']);
        }

        header("Content-Type:text/html;charset=utf-8");
        error_reporting(E_ALL);
        ini_set('display_errors', TRUE);
        ini_set('display_startup_errors', TRUE);
        //创建对象
        $excel = new PHPExcel();
        $excel->getActiveSheet()->setTitle('预约下单人员');
        //Excel表格式,这里简略写了8列
        $letter = array('A', 'B', 'C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S');
        //表头数组
        $tableheader = array('用户id','用户标识', '预约时间',  '状态', '手机号','订单号','创建时间','角色','姓名','大学','学院','学生号','宿舍名称');
        //填充表头信息
        for ($i = 0; $i < count($tableheader); $i++) {

            $excel->getActiveSheet()->setCellValue("$letter[$i]1", "$tableheader[$i]");
        }

        $data=json_decode(json_encode($data),true);
        //填充表格信息
        for ($i = 2; $i <= count($data) + 1; $i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key => $value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i", "$value");
                $j++;
            }
        }
        //创建Excel输入对象
        ob_end_clean();
        $objWriter = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        //多浏览器下兼容中文标题
        $fileName = '预约下单人员'.date("Y-m-d-h-i-s",time());
        $encoded_filename = urlencode($fileName);
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '.xls"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $fileName . '.xls"');
        } else {
            header('Content-Disposition: attachment; filename="' . $fileName . '.xls"');
        }
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');

    }


}